/**
 * $Revision: 1.0 $
 * $Author: Eric Yang $
 * $Date: Aug 9, 2009 10:55:58 PM $
 *
 * Author: Eric Yang
 * Date  : Aug 9, 2009 10:55:58 PM
 *
 */
package com.gooex.web.action.user;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.c4j.string.StringTools;
import org.c4j.system.web.Constants;
import org.c4j.system.web.cookie.CookieTools;

import com.gooex.domain.organization.User;
import com.gooex.web.action.BaseAnonymousAction;

/**
 * @author Eric Yang
 * @version 1.0
 */
public class LoginAction extends BaseAnonymousAction {

	private String account;

	private String password;

	private String fromurl;

	public String execute() throws Exception {
		User user = userManager.getUserByAccount(account);
		if (user != null) {
			if (user.authorize(password)) {
				sessionContext.setSessionFlag(user);
				addCookie(user);
				if (StringTools.isNotBlankOrNull(fromurl))
					return "back";
				return SUCCESS;
			}
		}
		CookieTools.clearCookie(Constants.COOKIE_LOGIN_PASSWORD);
		CookieTools.addCookie(Constants.COOKIE_LOGIN_NAME, account, 60 * 60);
		addActionError("user.name_or_password.wrong");
		return INPUT;
	}

	private void addCookie(User user) throws IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		String remberName = request.getParameter("remberName");
		String autoLogin = request.getParameter("autoLogin");
		// String host = request.getServerName();
		int cookieMaxAge = 7 * 24 * 60 * 60;

		// if ("true".equals(remberName) || "true".equals(autoLogin)) {
		CookieTools.addCookie(Constants.COOKIE_LOGIN_NAME, user.getEmail(), cookieMaxAge);
		// }
		if ("true".equals(autoLogin)) {
			CookieTools.addCookie(Constants.COOKIE_LOGIN_PASSWORD, user.getPassword(), cookieMaxAge);
		}
	}

	public void setAccount(String name) {
		this.account = name;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getFromurl() {
		return fromurl;
	}

	public void setFromurl(String fromurl) {
		this.fromurl = fromurl;
	}

}
